<template>
  <div style="overflow: hidden;">
    <div class="toubu" style="position: relative;">
      <el-button type="default" style="position: absolute; right: 0; top: 0;" @click="goBack">返回</el-button>
      <div style="display: flex; justify-content:center;">
        <!-- <div class="shangchuan">
          <a-input-group style="width: 380px;" compact>
            <a-input placeholder="请输入要生成二维码的链接..." v-model:value="dan_url" style="width: 280px" />
            <a-button @click="add_url" type="primary">插入链接</a-button>
          </a-input-group>
        </div> -->
        <!-- <el-button type="primary" @click="qrcode_click">生成二维码</el-button> -->
        <el-button type="success" @click="download_qrcode" :loading="load">二维码打包下载</el-button>
      </div>
      <!-- <div class="shezhi">
                <input type="file" id="filelogo" accept=".png,.jpg,.jpeg,.webp" style="display: none;"
                    @change="handleLogoChange" />
                <label for="filelogo" class="custom-file-label">上传二维码logo</label>

                <input type="file" id="filebg" accept=".png,.jpg,.jpeg,.webp" style="display: none;"
                    @change="handleBgChange" />
                <label for="filebg" class="custom-file-label">上传二维码背景图</label>

                <a-input addon-before="二维码边框(像素)" style="width: 200px; margin-right: 20px;"
                    v-model:value="qr_type.margin" placeholder="像素px" />

                <a-input addon-before="二维码尺寸(像素)" style="width: 200px; margin-right: 20px;" v-model:value="qr_type.size"
                    placeholder="像素px" />

                <span style="margin-right: 12px;">二维码密度:</span>

                <a-radio-group style="margin-right: 20px;" v-model:value="qr_type.errorLevel">
                    <a-radio-button value="0">L</a-radio-button>
                    <a-radio-button value="1">M</a-radio-button>
                    <a-radio-button value="2">Q</a-radio-button>
                    <a-radio-button value="3">H</a-radio-button>
                </a-radio-group>

                <a-checkbox v-model="qr_type.binarize">二值化处理</a-checkbox>
            </div> -->
    </div>


    <div class="qr-box">
      <div class="qr-code">
        <div style="margin-top: 16px; border: 1px solid #f1f1f1;" v-for="(item, index) in qr">
          <div class="qr-code-"
            style="justify-content: center; display: flex; flex-direction: column;align-items: center;">
            <vue-qr ref="qrcodeCanvasRef" :margin="qr_type.margin" :logoSrc="qr_type.icon"
              :correctLevel="Number(qr_type.errorLevel)" :text="item.src" :binarize="qr_type.binarize"
              :size="qr_type.size" :bgSrc="qr_type.bgSrc" :gifBgSrc="qr_type.gifBgSrc"></vue-qr>
            <div style="margin-bottom: 20px; font-size: 32px;">{{ item.title }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import html2canvas from 'html2canvas';
import JSZip from 'jszip'
import vueQr from 'vue-qr'

export default {
  name: 'generateQRcode',
  components: {
    'vue-qr': vueQr
  },
  data() {
    return {
      load: false,
      qrcodeCanvasRef: null,
      qr: [],
      qr_type: {
        type: 'canvas',
        icon: '',
        size: 400,
        bordered: false,
        margin: 20,
        errorLevel: '1',
        binarize: false, //二值化
        bgSrc: '',
        gifBgSrc: ''
      },
      url: 'https://qrcode.tfney.com?shell=',
      shellUrl: '',
      shellId: '',
      expireSocketCount: 0,
      chargingSocketCount: 0,
    }
  },
  created() {
    // 使用 this.$route.query 来访问查询参数
    // 假设 val 是一个对象，你需要访问它的具体属性
    console.log("获取到的查询参数 val:", this.$route.query);
    let chargeInfo = this.$route.query
    this.shellId = chargeInfo.shellId
    this.url = chargeInfo.qrcodeUrl
    this.shellUrl = chargeInfo.qrcodeUrl.replace("/socket", "")
    this.expireSocketCount = chargeInfo.expireSocketCount
    this.chargingSocketCount = chargeInfo.chargingSocketCount
    this.qrcode_click();
    // 如果 val 是具体的键，比如 val={key: "value"}，可以这样访问
    // console.log("特定查询参数的值:", this.$route.query.key);
  },
  methods: {
    qrcode_click() {
      if (this.shellId === '') {
        this.$message({
          message: '未查询到设备ID!',
          type: 'error',
          center: true
        });
        return;
      }
      this.qr.push({ src: `${this.shellUrl}${this.shellId}`, title: this.shellId });
      for (let index = 0; index < this.expireSocketCount + this.chargingSocketCount; index++) {
        // 直接计算 index1，如果 index 小于 9（即第10个元素之前），在前面加 '0'
        let srcIndex = index < 9 ? `0${index}` : `${index}`;
        let titleIndex = index < 9 ? `0${index + 1}` : `${index + 1}`;
        let src = `${this.url}${this.shellId}/${srcIndex}`;
        let title = `${this.shellId}/${titleIndex}`;
        this.qr.push({ src, title });
      }
      // this.qr.push({ src: this.url + this.shellId, title: this.shellId })
      // for (let index = 0; index < this.expireSocketCount + this.chargingSocketCount; index++) {
      //   let index1 = ''
      //   if (index >= 0 && index + 1 < 10) {
      //     index1 = index + 1
      //     index1 = '0' + index1
      //   } else {
      //     index1 = index + 1
      //   }
      //   let src = this.url + this.shellId + '/' + index1
      //   let title = this.shellId + '/' + index1
      //   this.qr.push({ src: src, title: title })
      // }
    },
    goBack() {
      this.$router.push({
        name: 'pileList',
        query: this.shellId
      })
    },
    async download_qrcode() {
      this.load = true; // 开始下载前，设置 loading 为 true
      // if (this.qr.length === 0) {
      //   this.$message({
      //     message: '请先生成二维码！',
      //     type: 'error',
      //     center: true
      //   });
      //   this.load = false; // 如果没有二维码可下载，设置 loading 为 false 并退出
      //   return;
      // }
      try {
        var zip = new JSZip();
        const qrCodes = document.querySelectorAll('.qr-code-');
        await Promise.all(Array.from(qrCodes).map(async (qrCode, index) => {
          const canvas = await html2canvas(qrCode, { scale: 1 });
          const imgData = canvas.toDataURL('image/png').split(',')[1];
          zip.file(`${this.qr[index].title}.png`, imgData, { base64: true });
        }));

        const content = await zip.generateAsync({ type: 'blob' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(content);
        link.download = this.shellId + '.zip';
        link.click();
      } catch (error) {
        console.error("下载二维码时发生错误:", error);
        this.$message({
          message: '下载二维码失败！',
          type: 'error',
          center: true
        });
      } finally {
        this.load = false; // 完成下载或发生错误后，设置 loading 为 false
        this.$router.back(-1)
      }
    },
    handleLogoChange(e) {
      this.qr_type.icon = URL.createObjectURL(e.target.files[0])
    },
    handleBgChange(e) {
      this.qr_type.bgSrc = URL.createObjectURL(e.target.files[0])
    },
  }
}
</script>

<style scoped>
.custom-file-label {
  display: inline-block;
  padding: 8px 10px 8px 10px;
  background: #0d6df3;
  border-radius: 5px;
  color: #fff;
  font-size: 14px;
  margin-right: 10px;
  cursor: pointer;
  transition: all 0.2s;
  /* 过度 */
  -moz-transition: all 0.2s;
  /* Firefox */
  -webkit-transition: all 0.2s;
  /* Safari 和 Chrome */
}

.custom-file-label:hover {
  background: #3a82e8;
}

.shezhi {
  margin-left: 20px;
  height: 50px;
  display: flex;
  align-items: center;
}

.shangchuan {
  height: 50px;
  margin-left: 20px;
  margin-top: 6px;
  display: flex;
  align-items: center;
}


.qr-code {
  width: auto;
  /* height: calc(100vh - 153px); */
  height: auto;
  display: flex;
  justify-content: space-between;
  align-content: flex-start;
  flex-wrap: wrap;
  overflow-y: scroll;
}

.qr-box {
  display: flex;
}

.excel-list {
  margin-left: 16px;
  width: 50%;
  height: calc(100vh - 153px);
  overflow-y: scroll;
}
</style>
